#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:jidi
@file:portal_http_api.py
@time:2022/08/14
"""
import json
from dataclasses import asdict

import requests

from service.wework.api.calendar_http_api import CalendarHttpApi
from service.wework.model.calendar import Calendar
from service.wework.model.portal import Portal
from service.wework.utils.log import log


class PortalHttpApi(Portal):
    def add_calendar(self, calendar: Calendar):
        log.debug({'calendar': calendar})

        r = requests.post(
            'https://qyapi.weixin.qq.com/cgi-bin/oa/calendar/add',
            params={'access_token': self.session.get_token()},
            json={'calendar': asdict(calendar)}
        )
        log.debug('add_calendar')
        log.debug(r.json())
        return r

    def list(self, *calendar_id_list):
        # wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA
        r = requests.post(
            'https://qyapi.weixin.qq.com/cgi-bin/oa/calendar/get',
            params={'access_token': self.session.get_token()},
            json={
                'cal_id_list': calendar_id_list
            }
        )

        calendar_list = []
        for item in r.json()['calendar_list']:
            calendar = Calendar()
            calendar.summary = item['summary']
            calendar.color = item['color']
            calendar.organizer = item['organizer']
            calendar_list.append(calendar)

        return calendar_list

    def get(self, calendar_id):
        calendar = self.list(calendar_id)[0]
        return CalendarHttpApi(self.session, calendar)